from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from django_filters import FilterSet,filters
from myclass import myclass_seralizers,models
from  rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.pagination import PageNumberPagination
from django_filters import FilterSet,filters
# Create your views here.

class MyFilter(FilterSet):
    addtime=filters.DateFilter(field_name='addtime',lookup_expr='te')
    class Meta:
        fields=['title','clas']
        model=models.GoodsModel

class MyPage(PageNumberPagination):
        page_size_query_param = 'size'



class Goods(ListAPIView):

        queryset = models.GoodsModel.objects.all()
        serializer_class = myclass_seralizers.GoodsSer
        filter_backends = [DjangoFilterBackend]
        filterset_class=MyFilter
        pagination_class = MyPage


class Class(ListAPIView):
        queryset = models.ClassModel.objects.all()
        serializer_class = myclass_seralizers.ClassSer


class Info(APIView):
    def get(self,request):
        id=request.query_params.get('id')
        info=models.GoodsModel.objects.filter(id=id).first()
        ser=myclass_seralizers.GoodsSer(instance=info)
        if ser:
            return Response({'code':200,'data':ser.data})
        else:
            return Response({'code':400,'msg':ser.errors})




class Add(APIView):
    def post(self,request):
        ser=myclass_seralizers.GoodsSer(data=request.data)

        print(ser)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'data': ser.data})



        return Response({'code':400,'msg':'添加失败'})


from django.core.files.storage import default_storage
class Images(APIView):
    def post(self,request):
        file=request.data.get('file')
        types=['png','jpg']
        if file.name.split('.')[-1] not in types:
            return Response({'code':201,'msg':'文件类型错误'})
        if file.size>1024*1024*2:
            return Response({'code':201,'msg':'文件过大'})
        #通过default_storage 设置文件上传的文件路径 ， 文件名字，文件对象
        uploadfile=default_storage.save(file.name,file)
        url=default_storage.url(uploadfile)#捕获上传后的位置
        return Response({'url':url})
